// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const usersDb = cloud.database().collection('users')
  const userData = await usersDb.where({
    openid
  }).get()
  const user = userData.data[0]
  // 可借阅总时长
  const keepTime = user.keepTime * 24 * 1000 * 3600

  const books = user.books
  const booksDb = cloud.database().collection('books')
  const booksDetail = []
  for (let i = 0; i < books.length; i++) {
    const book = await booksDb.where({
      bookId: books[i].bookId
    }).get()
    book.data[0].overtime = (Date.now() - user.books[i].borrowTime > keepTime)
    book.data[0].remainTime = keepTime - (Date.now() - user.books[i].borrowTime)
    booksDetail.push(book.data[0])
  }

  return booksDetail
}